<template lang="pug">
  .toanywhere
    .btn(v-on:mouseenter="animat = true;scrollTo('top', 80, 'Linear', true)", v-on:mouseleave='animat = false', @click='scrollTo("top")')
      svg.icon(aria-hidden="true")
        use(xlink:href="#icon-angle-up")
    .btn(v-on:mouseenter="animat = true;scrollTo('bottom', 80, 'Linear', true)", v-on:mouseleave='animat = false', @click='scrollTo("bottom")')
      svg.icon(aria-hidden="true")
        use(xlink:href="#icon-angle-down")
</template>

<script>
  export default {
    data () {
      return {
        animat: true,
        maxScrollHeight: 0
      }
    },
    computed: {
      _scrollTop () {
        return this.$store.state.view.scrollTop
      }
    },
    methods: {
      // y： 目标位置 t： 时间 animat：动画 step：是否是直接到达目标位置
      scrollTo (y, t = 500, animat = 'Quart.easeOut', step = false) {
        const now = this._scrollTop

        if (y === 'bottom') {
          const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
          const innerHeight = window.innerHeight !== undefined ? window.innerHeight : Math.min(document.documentElement.clientHeight, document.body.clientHeight)
          this.maxScrollHeight = scrollHeight - innerHeight
        }

        // 渐进式 滚动 向上
        if (step && y == 'top') {
          if (now == 0) {
            this.animat = false
            return
          }
          let _y = 0
          if (now >= 10) { _y = now - 10 }
          this.animation = Math.animation(now, _y, (value, end) => {
            window.scrollTo(0, value)
            if (end && this.animat && now != 0) {
              this.scrollTo(y, t, animat, true)
            }
          }, animat, t)
          return

        // 渐进式 滚动 向下
        } else if (step && y == 'bottom') {
          if (now >= this.maxScrollHeight - 1) {
            this.animat = false
            return
          }
          let _y = this.maxScrollHeight
          if (now <= this.maxScrollHeight - 10) { _y = now + 10 }
          this.animation = Math.animation(now, _y, (value, end) => {
            window.scrollTo(0, value)
            if (end && this.animat && now != this.maxScrollHeight) {
              this.scrollTo(y, t, animat, true)
            }
          }, animat, t)
          return
        }

        // 直接滚到任意位置
        if (y === 'top') {
          y = 0
        } else if (y === 'bottom') {
          y = this.maxScrollHeight
        }
        
        Math.animation(now, y, function (value) {
          window.scrollTo(0, value)
        }, animat, t)
      }
    }
  }
</script>

<style lang="stylus" scoped>
.toanywhere
  position fixed
  bottom 50px
  left 50%
  transform translateX(500px)
  border 1px solid $dWhite
  .btn
    background $White
    padding .05rem .07rem
    cursor pointer
    &:first-child
      border-bottom 1px solid $dWhite
    &:hover
      background $elSilver
      .icon
        opacity .9
    .icon
      width .2rem
      height .2rem
      opacity .6
</style>

